/*
 * @Description: 资源信息
 * @Author: DHL
 * @Date: 2022-03-14 17:13:43
 * @LastEditors: DHL
 * @LastEditTime: 2022-08-24 13:12:54
 */

import { defineComponent, computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { cloneDeep, assign } from 'lodash-es'
import { ResourceModel } from '/@/api/system/model/resourceModel'
import { apiResourceSave, apiResourceUpdateById } from '/@/api/system/resource'
import { log } from '/@/utils/log'
import resourceSelectIcon from '/@/icons/iconPreview.vue'

export default defineComponent({
  name: 'ResourceForm',
  components: { resourceSelectIcon },
  emits: ['refreshTableData'],
  setup(props, { emit, expose }) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////
    const dbFormRef = ref()
    const loading = ref(true)

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 显示弹框
     */
    const visible = ref(false)

    /**
     * 标题
     */
    const title = computed(() => {
      let rtn = ''
      switch (action.value) {
        case 'add':
          rtn = '新增'
          break
        case 'edit':
          rtn = '编辑'
          break
        default:
          rtn = '查看'
          break
      }
      return rtn
    })

    /**
     * 公共
     */
    const commonObj = reactive({
      oldId: '', // 编辑时保存原资源ID
      projectId: '',
      projectName: '',
      parentResId: '',
      parentResName: ''
    })

    //////////////////////////////////////////////////
    // 表单
    //////////////////////////////////////////////////

    const defaultForm = {
      id: '',
      parentResId: '', // 父级编码
      name: '', // 资源名称
      url: '', // 资源路径
      resType: '1', // 资源类型
      iconCls: '', // 资源图标
      resSeq: 0, // 顺序
      target: '1', // 目标
      openType: '1', // 主窗口打开模式
      description: '', // 资源描述
      status: '1', // 资源状态(0：无效；1：有效)
      islog: '1', // 是否记录日志（0：无效；1：有效）
      iscache: '0', // 是否缓存（0-否，1-是）
      projectId: '' // 项目ID
    }

    let dbForm = reactive<ResourceModel>(cloneDeep(defaultForm))

    //////////////////////////////////////////////////
    // 表单验证规则
    //////////////////////////////////////////////////

    /**
     * 表单验证规则
     */
    const rules = reactive({
      id: [
        {
          required: true,
          message: '请输入资源编码',
          trigger: 'blur'
        }
      ],
      name: [
        {
          required: true,
          message: '请输入资源编码',
          trigger: 'blur'
        }
      ],
      url: [
        {
          required: false,
          message: '请输入资源路径',
          trigger: 'blur'
        }
      ],
      resType: [
        {
          required: true,
          message: '请选择资源类型',
          trigger: 'blur'
        }
      ],
      iconCls: [
        {
          required: false,
          message: '请输入资源图标',
          trigger: 'blur'
        }
      ],
      resSeq: [
        {
          required: true,
          message: '请输入顺序',
          trigger: 'blur'
        }
      ],
      target: [
        {
          required: false,
          message: '请输入目标',
          trigger: 'blur'
        }
      ],
      description: [
        {
          required: false,
          message: '请输入资源描述',
          trigger: 'blur'
        }
      ],
      status: [
        {
          required: true,
          message: '请选择资源状态',
          trigger: 'blur'
        }
      ],
      islog: [
        {
          required: true,
          message: '请选择是否记录日志',
          trigger: 'blur'
        }
      ],
      iscache: [
        {
          required: true,
          message: '请选择是否缓存',
          trigger: 'blur'
        }
      ]
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 打开弹框
     */
    function handleOpen(
      actionParam: string,
      rowParam: ResourceModel,
      selectRowParam: ResourceModel,
      parentNames: Array<string>
    ) {
      visible.value = true
      loading.value = false
      action.value = actionParam

      assign(dbForm, cloneDeep(rowParam))

      if (actionParam === 'add') {
        assign(commonObj, {
          projectId: rowParam.projectId,
          projectName: rowParam.projectName,
          parentResId: selectRowParam.id,
          parentResName: parentNames.join(' - ')
        })
      } else {
        commonObj.oldId = rowParam.id === undefined ? '' : rowParam.id
        assign(commonObj, {
          projectId: rowParam.projectId,
          projectName: rowParam.projectName,
          parentResId: selectRowParam.parentResId,
          parentResName: parentNames.join(' - ')
        })
      }
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      assign(dbForm, cloneDeep(defaultForm))
      visible.value = false
    }

    /**
     * 提交表单
     */
    function handleSubmit(isContinue: boolean) {
      assign(dbForm, {
        projectId: commonObj.projectId,
        parentResId: commonObj.parentResId
      })

      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          if (action.value === 'add') {
            addFun(isContinue)
          } else {
            editFun()
          }
        } else {
          log.warn('资源管理', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun(isContinue: boolean) {
      loading.value = true
      apiResourceSave(dbForm)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)

            handleReset(!isContinue)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun() {
      loading.value = true
      dbForm.oldId = commonObj.oldId
      apiResourceUpdateById(dbForm)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)

            handleReset(true)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 重置表单
     * @param isClosed 是否关闭弹框
     */
    function handleReset(isClosed: boolean) {
      assign(dbForm, cloneDeep(defaultForm))
      if (isClosed) {
        emit('refreshTableData')
        visible.value = false
      }
    }

    /**
     * 资源类型改变事件
     * @param val
     */
    function handleResTypeChange(val: string) {
      if (val !== '0') {
        assign(dbForm, {
          target: '1', // 目标
          openType: '1' // 主窗口打开模式
        })
      }
    }

    //////////////////////////////////////////////////
    // icon
    //////////////////////////////////////////////////

    const resourceSelectIconRef = ref()

    /**
     * 选择图标回调
     */
    function handleOpenIcon() {
      resourceSelectIconRef.value.handleOpen()
    }

    /**
     * 选择图标回调
     */
    function handleSelectIcon(iconNameParam: string) {
      dbForm.iconCls = iconNameParam
    }

    //////////////////////////////////////////////////
    // 生命周期
    //////////////////////////////////////////////////
    onMounted(() => { })

    /**
     * 暴露函数
     */
    expose({ handleOpen })

    return {
      loading,
      visible,
      action,
      title,
      dbFormRef,
      dbForm,
      rules,
      commonObj,
      handleOpen,
      handleClose,
      handleSubmit,
      handleReset,
      resourceSelectIconRef,
      handleOpenIcon,
      handleSelectIcon,
      handleResTypeChange
    }
  }
})
